import axios from 'axios';
import { useUserStore } from '../stores/user';

const api = axios.create({
  baseURL: '/api',
  timeout: 5000
});

// 请求拦截器：添加token
api.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器：处理token过期
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      const userStore = useUserStore();
      userStore.logout();
    }
    return Promise.reject(error);
  }
);

export interface RegisterData {
  username: string;
  phone: string;
  password: string;
}

export interface LoginData {
  username?: string;
  phone?: string;
  password: string;
}

export interface LoginResponse {
  token: string;
  user: {
    id: number;
    username: string;
    phone: string;
  };
}

// 注册
export const register = async (data: RegisterData) => {
  const response = await api.post<LoginResponse>('/auth/register', data);
  return response.data;
};

// 登录
export const login = async (data: LoginData) => {
  const response = await api.post<LoginResponse>('/auth/login', data);
  return response.data;
};

// 获取用户信息
export const getUserInfo = async () => {
  const response = await api.get('/user/info');
  return response.data;
}; 